/**
 * Copyright (C) 2010 Alfredo Morresi
 * 
 * This file is part of SmsForFree project.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; If not, see <http://www.gnu.org/licenses/>.
 */

package it.rainbowbreeze.libs.logic;

import it.rainbowbreeze.libs.common.RainbowLogFacility;
import it.rainbowbreeze.libs.common.RainbowResultOperation;
import android.content.Context;
import android.os.Handler;

import static it.rainbowbreeze.libs.common.RainbowContractHelper.*;

/**
 * Read the log related to the application. Could then used for email, report etc
 * 
 * @author Alfredo "Rainbowbreeze" Morresi
 */
public class RainbowPrepareLogToSendThread
	extends RainbowBaseBackgroundThread<String>
{
	protected final RainbowLogFacility mBaseLogFacility;
	protected final String mLogTagToSearch;
	protected final RainbowCrashReporter mBaseCrashReporter;

	//---------- Constructors
	public RainbowPrepareLogToSendThread(
			Context context,
			Handler handler,
			RainbowLogFacility logFacility,
			RainbowCrashReporter crashReporter,
			String logTagToSearch)
	{
		super(context, handler);
		mBaseLogFacility = checkNotNull(logFacility, "LogFacility");
		mBaseCrashReporter = checkNotNull(crashReporter, "CrashReporter");
		mLogTagToSearch = checkNotNullOrEmpty(logTagToSearch, "LogTag to search");
	}




	//---------- Private fields

	
	

	//---------- Public fields
	public final static int WHAT_PREPARELOGTOSEND = 1010;
	



	//---------- Public methods
	@Override
	public void run() {
		//collect all the log (normal log + crash report)
//		mResultOperation = LogFacility.getLogData(new String[]{ GlobalDef.LOG_TAG, "AndroidRuntime"});
		RainbowResultOperation<String> resLog = mBaseLogFacility.getLogData(new String[]{mLogTagToSearch});
		RainbowResultOperation<String> resCrash = mBaseCrashReporter.getPreviousCrashReports(getContext());
		
		//merge two results
		if (!resLog.hasErrors() && !resCrash.hasErrors()) {
			mResultOperation = new RainbowResultOperation<String>(resCrash.getResult() + resLog.getResult());
		} else if (!resLog.hasErrors()) {
			mResultOperation = resLog;
		} else if (!resCrash.hasErrors()) {
			mResultOperation = resCrash;
		} else {
			mResultOperation = new RainbowResultOperation<String>();
		}
		
		callHandlerAndRetry(WHAT_PREPARELOGTOSEND);
	}
	



	//---------- Private methods
}
